package com.centling;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class SessionInfoServlet extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		/*
		 * Returns the current HttpSession associated with this request or, 
		 * if if there is no current session and create is true, returns a new session. 
		If create is false and the request has no valid HttpSession, this method returns null. 
		To make sure the session is properly maintained,
		 you must call this method before the response is committed. 
		 If the container is using cookies to maintain session integrity 
		 and is asked to create a new session when the response is committed, 
		 an IllegalStateException is thrown.
		 */
		
		/*
		 * 可以通过禁止浏览器cookie观察，每次请求都会创建新的jessionid
		 * 如果不禁止浏览器cookie，那么第一次创建后，以后都不会创建
		 */
		/*
		 * session不像cookie一样存在路径的问题，在其他路径获取不到session 的问题
		 * 同一个application下，同一个窗口就可以获取同一个session
		 */
		HttpSession session = req.getSession(true);
		
		resp.setContentType("text/html");
		
		PrintWriter writer = resp.getWriter();
		String id = session.getId();
		
		long createTime = session.getCreationTime();
		Date d = new Date(createTime);
		
		int maxInactiveInterval = session.getMaxInactiveInterval();//最大控件间隔，单位是秒
		
		
		writer.write("jessionId:"+id);
		writer.write("<br/>");
		
		writer.write("createTime:"+d);
		writer.write("<br/>");
		
		writer.write("maxInactiveInterval:"+maxInactiveInterval);
		writer.write("<br/>");
		
		/*
		 * 这边两种，一种是没有encodeURL没有重写url的，没有重写url的，url后边不会跟着jsessionid
		 * 一种是重写url的，重写url的在url后边会跟着jessionid
		 */
		/*
		writer.write("<a href = \"sessioninfoservlet\">"+"refresh</a>");
		writer.write("<br/>");
		*/
		//重写url演示：浏览器禁止cookie，然后点击refresh超链接
		//<a href="sessioninfoservlet;jsessionid=770F2B07D60C7B55FAA3895F0B62397C">refresh</a>
		writer.write("<a href = \""+resp.encodeURL("sessioninfoservlet")+"\">"+"refresh</a>");
		writer.write("<br/>");
		
	}
}
